<template>
  <div class="tab-wrap">
    <div
      :class="[{ active: value === item.value }, 'tab']"
      v-for="item in options"
      :key="item.value"
      @click="handleClick(item)"
      :data-value="item.value"
    >
      {{ item.label }}
    </div>
    <div id="line" />
  </div>
</template>

<script>
export default {
  props: {
    options: {
      type: Array,
      default: () => [
        { value: 0, label: "测试0" },
        { value: 1, label: "测试1" },
        { value: 2, label: "测试2" },
        { value: 3, label: "测试3" },
        { value: 4, label: "测试4" },
      ],
    },
    value: {
      type: [String, Number],
      default: 0,
    },
  },
  data() {
    return {};
  },
  components: {},
  computed: {},
  created() {},
  mounted() {},
  watch: {
    value: {
      handler(value) {
        this.move(value);
      },
      immediate: true,
    },
  },
  methods: {
    handleClick({ value, label }) {
      if (this.value === value) return;
      this.$emit("input", value);
      this.$emit("tab-click", { value, label });
    },
    move(value) {
      this.$nextTick(() => {
        let arr = document.getElementsByClassName("tab");
        let target = [].find.call(
          arr,
          (item) => item.dataset.value === String(value)
        );
        if (!target) return;
        let left = target.offsetLeft;
        let width = target.offsetWidth;
        let line = document.getElementById("line");
        line.style.width = width + "px";
        line.style.transform = `translateX(${left + "px"})`;
      });
    },
  },
};
</script>

<style scoped>
.tab-wrap {
  display: flex;
  align-items: center;
  position: relative;
  box-sizing: border-box;
  margin-bottom: 15px;
  margin-top: -30px;
}
/* .tab-wrap::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 2px;
  background-color: #e4e7ed;
  z-index: 1;
} */
#line {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 100%;
  background-color: #409eff;
  z-index: 1;
  transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  z-index: 2;
  border-radius: 5px;
}
.tab {
  text-align: center;
  height: 50px;
  line-height: 50px;
  font-weight: 500;
  color: #303133;
  box-sizing: border-box;
  margin: 0 5px;
  padding: 0 10px;
  cursor: pointer;
  position: relative;
  z-index: 10;
}
.tab:hover {
  color: #409eff;
}
.tab.active {
  color: #fff;
}
.tab:first-child {
  margin-left: 0;
}
</style>
